#include "..\headers\ListOf.h"

// Define the structure of a TreeNode

struct TreeNode {
  int val;
  struct TreeNode* left;
  struct TreeNode* right;
};

// Create a new TreeNode and store the value passed in the parameter

struct TreeNode* createNode(int val) {
  struct TreeNode* node = (struct TreeNode*)malloc(sizeof(struct TreeNode));
  node->val = val;
  node->left = NULL;
  node->right = NULL;
  return node;
}

// Function to print the tree in level order
void levelOrder(struct TreeNode* root, int n) {
  struct TreeNode* queue[100];
  int front = 0, rear = 0;
  queue[rear++] = root;
  while (front < rear) {
    struct TreeNode* Node = queue[front++];
    printf("%d", Node->val);
    if (front != n) printf(" ");
    if (Node->left != NULL) queue[rear++] = Node->left;
    if (Node->right != NULL) queue[rear++] = Node->right;
  }
}

// Function to construct a BST from the given inorder and preorder traversals

struct TreeNode* constructBST(int inOrder[], int preOrder[], int inStart,
                              int inEnd, int preStart, int preEnd) {
  // If the inorder array is empty, return NULL
  if (inStart > inEnd || preStart > preEnd) return NULL;

  // Create a new TreeNode and store the value of the root in it
  struct TreeNode* root = createNode(preOrder[preStart]);

  // Find the index of the root in the Inorder array
  int rootIndex = inStart;
  while (inOrder[rootIndex] != preOrder[preStart]) rootIndex++;

  // Construct the left subtree recursively
  root->left = constructBST(inOrder, preOrder, inStart, rootIndex - 1,
                            preStart + 1, preStart + rootIndex - inStart);

  // Construct the right subtree recursively
  root->right = constructBST(inOrder, preOrder, rootIndex + 1, inEnd,
                             preStart + rootIndex - inStart + 1, preEnd);

  // Return the root of the tree
  return root;
}

// Function to mirror the given BST
struct TreeNode* mirrorTree(struct TreeNode* root) {
  if (root == NULL) return NULL;
  struct TreeNode* temp = root->left;
  root->left = root->right;
  root->right = temp;
  mirrorTree(root->left);
  mirrorTree(root->right);
  return root;
}

int main() {
  int preOrder[31];
  int inOrder[31];  // Array to store the in-order traversal of the BST
  int n;            // Store the number of nodes in the BST
  scanf("%d", &n);  // Get the number of nodes from the user
  if (n == 0) return 0;
  for (int i = 0; i < n; i++)
    scanf("%d", &inOrder[i]);  // Get the in-order traversal from the user
  for (int i = 0; i < n; i++) scanf("%d", &preOrder[i]);

  struct TreeNode* root = constructBST(inOrder, preOrder, 0, n - 1, 0, n - 1);

  mirrorTree(root);

  levelOrder(root, n);

  return 0;
}